package com.gzjh_group.photoalbum;

import com.alibaba.fastjson.JSON;
import com.zhy.http.okhttp.callback.Callback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public abstract class HttpCallBack<T> extends Callback<T> {

    private Class<T> persistentClass;

    public HttpCallBack(){
        this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);
    }

    public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {

        //返回表示此 Class 所表示的实体（类、接口、基本类型或 void）的直接超类的 Type。
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        //返回表示此类型实际类型参数的 Type 对象的数组。
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }

        return (Class) params[index];
    }

    @Override
    public T parseNetworkResponse(Response response, int id) throws Exception {
        return JSON.parseObject(response.body().string(), persistentClass);
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        onFailure(call, e, id);
    }

    @Override
    public void onResponse(T response, int id){
        onSuccess(response, id);
    }

    @Override
    public void onBefore(Request request, int id) {
        super.onBefore(request, id);

    }

    public abstract void onFailure(Call call, Exception e, int id);

    public abstract void onSuccess(T response, int id);

}
